# -*- coding: utf-8 -*-
"""
Web应用配置管理

集中管理FastAPI应用的所有配置，包括：
- 服务器配置
- 数据库配置
- 安全配置
- CORS配置
- 日志配置
"""

import os
from typing import List, Optional
from functools import lru_cache
from pydantic import field_validator, Field
try:
    from pydantic_settings import BaseSettings
except ImportError:
    from pydantic import BaseSettings


class Settings(BaseSettings):
    """应用配置"""
    
    # 应用基础配置
    APP_NAME: str = "CRM旅游管理系统"
    VERSION: str = "2.0.0"
    DEBUG: bool = Field(default=False, env="DEBUG")
    
    # 服务器配置
    HOST: str = Field(default="0.0.0.0", env="HOST")
    PORT: int = Field(default=8000, env="PORT")
    
    # 安全配置
    SECRET_KEY: str = Field(..., env="SECRET_KEY")
    ACCESS_TOKEN_EXPIRE_MINUTES: int = Field(default=60 * 24 * 8, env="ACCESS_TOKEN_EXPIRE_MINUTES")  # 8天
    ALGORITHM: str = "HS256"
    
    # 密码配置
    PASSWORD_MIN_LENGTH: int = 8
    PASSWORD_HASH_ROUNDS: int = 12
    
    # Redis配置（验证码缓存）
    REDIS_URL: str = Field(default="redis://localhost:6379/0", env="REDIS_URL")
    REDIS_PASSWORD: Optional[str] = Field(default=None, env="REDIS_PASSWORD")
    
    # 验证码配置
    CAPTCHA_EXPIRE_SECONDS: int = Field(default=300, env="CAPTCHA_EXPIRE_SECONDS")  # 5分钟
    LOGIN_FAIL_THRESHOLD: int = Field(default=3, env="LOGIN_FAIL_THRESHOLD")  # 登录失败阈值
    LOGIN_FAIL_LOCK_SECONDS: int = Field(default=1800, env="LOGIN_FAIL_LOCK_SECONDS")  # 30分钟锁定
    
    # CORS配置
    BACKEND_CORS_ORIGINS: List[str] = Field(default_factory=lambda: ["http://localhost:3000", "http://localhost:8080"])
    
    # 可信主机配置  
    ALLOWED_HOSTS: List[str] = Field(default_factory=lambda: ["localhost", "127.0.0.1"])
    
    # 数据库配置
    DATABASE_URL: str = Field(..., env="DATABASE_URL")
    DATABASE_POOL_SIZE: int = Field(default=20, env="DATABASE_POOL_SIZE")
    DATABASE_MAX_OVERFLOW: int = Field(default=30, env="DATABASE_MAX_OVERFLOW")
    
    # Redis通用配置
    REDIS_EXPIRE_TIME: int = Field(default=3600, env="REDIS_EXPIRE_TIME")  # 1小时
    
    # 文件上传配置
    MAX_FILE_SIZE: int = Field(default=10 * 1024 * 1024, env="MAX_FILE_SIZE")  # 10MB
    UPLOAD_DIR: str = Field(default="uploads", env="UPLOAD_DIR")
    ALLOWED_FILE_TYPES: List[str] = Field(default_factory=lambda: ["image/jpeg", "image/png", "application/pdf", "application/vnd.ms-excel"])
    
    # 邮件配置
    SMTP_SERVER: Optional[str] = Field(default=None, env="SMTP_SERVER")
    SMTP_PORT: int = Field(default=587, env="SMTP_PORT")
    SMTP_USERNAME: Optional[str] = Field(default=None, env="SMTP_USERNAME")
    SMTP_PASSWORD: Optional[str] = Field(default=None, env="SMTP_PASSWORD")
    SMTP_USE_TLS: bool = Field(default=True, env="SMTP_USE_TLS")
    
    # 短信配置
    SMS_PROVIDER: Optional[str] = Field(default=None, env="SMS_PROVIDER")
    SMS_ACCESS_KEY: Optional[str] = Field(default=None, env="SMS_ACCESS_KEY")
    SMS_SECRET_KEY: Optional[str] = Field(default=None, env="SMS_SECRET_KEY")
    
    # 日志配置
    LOG_LEVEL: str = Field(default="INFO", env="LOG_LEVEL")
    LOG_FILE: str = Field(default="logs/crm.log", env="LOG_FILE")
    LOG_MAX_SIZE: int = Field(default=10 * 1024 * 1024, env="LOG_MAX_SIZE")  # 10MB
    LOG_BACKUP_COUNT: int = Field(default=5, env="LOG_BACKUP_COUNT")
    
    # API配置
    API_V1_PREFIX: str = "/api/v1"
    API_DOCS_URL: str = "/docs"
    API_REDOC_URL: str = "/redoc"
    
    # 分页配置
    DEFAULT_PAGE_SIZE: int = 20
    MAX_PAGE_SIZE: int = 100
    
    # 缓存配置
    CACHE_TTL: int = Field(default=300, env="CACHE_TTL")  # 5分钟
    
    # 监控配置
    ENABLE_METRICS: bool = Field(default=True, env="ENABLE_METRICS")
    METRICS_PATH: str = "/metrics"
    
    @field_validator("SECRET_KEY", mode="before")
    @classmethod
    def validate_secret_key(cls, v: str) -> str:
        """验证密钥"""
        if not v or len(v) < 32:
            raise ValueError("SECRET_KEY必须至少32个字符")
        return v
    
    
    
    # 旅游业务配置
    REFRESH_TOKEN_EXPIRE_DAYS: int = Field(default=30, env="REFRESH_TOKEN_EXPIRE_DAYS")
    TOURISM_SEASON_HIGH: str = Field(default="04-01,10-31", env="TOURISM_SEASON_HIGH")
    TOURISM_SEASON_LOW: str = Field(default="11-01,03-31", env="TOURISM_SEASON_LOW")
    DEFAULT_TOUR_INSURANCE: bool = Field(default=True, env="DEFAULT_TOUR_INSURANCE")
    MIN_GROUP_SIZE: int = Field(default=8, env="MIN_GROUP_SIZE")
    MAX_GROUP_SIZE: int = Field(default=35, env="MAX_GROUP_SIZE")
    BOOKING_ADVANCE_DAYS: int = Field(default=7, env="BOOKING_ADVANCE_DAYS")
    NOTIFICATION_EMAIL_ENABLED: bool = Field(default=True, env="NOTIFICATION_EMAIL_ENABLED")
    NOTIFICATION_SMS_ENABLED: bool = Field(default=True, env="NOTIFICATION_SMS_ENABLED")
    EMERGENCY_CONTACT_PHONE: str = Field(default="400-888-9999", env="EMERGENCY_CONTACT_PHONE")

    class Config:
        env_file = ".env"
        case_sensitive = True
        # 允许额外的字段
        extra = "ignore"


@lru_cache()
def get_settings() -> Settings:
    """获取配置实例（单例模式）"""
    return Settings()


# 配置实例
settings = get_settings()